<template>
  <view class="wrap page-background">
    <CustomNavbar title="推荐"></CustomNavbar>
    <u-back-top :scroll-top="scrollTop"></u-back-top>
    <u-waterfall v-model="flowList" ref="uWaterfallRef">
      <template #left="{ leftList }">
        <view
          @click="toPreview(item)"
          class="demo-warter"
          v-for="(item, index) in leftList"
          :key="index"
        >
          <!-- 警告：微信小程序中需要hx2.8.11版本才支持在template中结合其他组件，比如下方的lazy-load组件 -->
          <u-lazy-load
            threshold="-450"
            border-radius="10"
            :image="item.image"
            :index="index"
          ></u-lazy-load>
          <view class="demo-info">
            <view class="demo-title">
              {{ item.title }}
            </view>
            <view class="demo-price"> 评分: {{ item.price }} </view>
            <view class="demo-tag">
              <view class="demo-tag-owner">
                {{ item.classname }}
              </view>
              <view class="demo-tag-text">
                {{ item.tabs[0] || '精选' }}
              </view>
            </view>
            <view class="demo-shop">
              {{ item.shop }}
            </view>
            <u-icon
              name="close-circle-fill"
              color="#fa3534"
              size="34"
              class="u-close"
              @click="remove(item.id)"
            ></u-icon>
          </view>
        </view>
      </template>
      <template #right="{ rightList }">
        <view
          @click="toPreview(item)"
          class="demo-warter"
          v-for="(item, index) in rightList"
          :key="index"
        >
          <!-- 警告：微信小程序中需要hx2.8.11版本才支持在template中结合其他组件，比如下方的lazy-load组件 -->
          <u-lazy-load
            threshold="-450"
            border-radius="10"
            :image="item.image"
            :index="index"
          ></u-lazy-load>
          <view class="demo-info">
            <view class="demo-title">
              {{ item.title }}
            </view>
            <view class="demo-price"> 评分: {{ item.price }} </view>
            <view class="demo-tag">
              <view class="demo-tag-owner">
                {{ item.classname }}
              </view>
              <view
                class="demo-tag-text"
                v-for="(tab, index) in item.tabs"
                :key="index"
              >
                {{ tab || '精选' }}
              </view>
            </view>
            <view class="demo-shop">
              {{ item.shop }}
            </view>
            <u-icon
              name="close-circle-fill"
              color="#fa3534"
              size="34"
              class="u-close"
              @click="remove(item.id)"
            ></u-icon>
          </view>
        </view>
      </template>
    </u-waterfall>
    <u-loadmore
      bg-color="rgb(240, 240, 240)"
      :status="loadStatus"
      @loadmore="fetchCategoryData"
    ></u-loadmore>
  </view>
</template>

<script setup>
  import CustomNavbar from '@/components/UI/custom.vue';
  import { ref } from 'vue';
  import { onLoad, onReachBottom, onPageScroll } from '@dcloudio/uni-app';
  import { getCategoryAPI } from '@/api/category.js';

  const loadStatus = ref('loadmore');
  const flowList = ref([]);
  const uWaterfallRef = ref();
  const isLoading = ref(false);
  const scrollTop = ref(0);
  import { useClassStore } from '@/stores/class';
  const classStore = useClassStore();

  // 转换API数据为瀑布流格式
  function transformApiData(apiData) {
    return apiData.map(item => ({
      id: item._id,
      title: item.description,
      image: item.smallPicurl.replace(/`/g, ''), // 移除URL中的反引号
      price: item.score,
      shop: item.nickname,
      tabs: item.tabs,
      classname: item.classname,
    }));
  }

  // 获取分类数据
  async function fetchCategoryData() {
    if (isLoading.value) return;

    isLoading.value = true;
    loadStatus.value = 'loading';

    try {
      const res = await getCategoryAPI();

      if (res.errCode === 0 && res.data) {
        // 这里就是简单的额写一下就这样了 此接口随机返回的壁纸一般都是在某个时间范围内是一定的 随机返回九张
        classStore.setTotal(9);
        // 这里是set不是add
        classStore.setCategoryDetailList(res.data);
        const newData = transformApiData(res.data);

        if (newData.length > 0) {
          flowList.value.push(...newData);
          loadStatus.value = 'loadmore';
        } else {
          loadStatus.value = 'nomore';
        }
      } else {
        uni.showToast({
          title: res.errMsg || '获取数据失败',
          icon: 'none',
        });
        loadStatus.value = 'loadmore';
      }
    } catch (error) {
      console.error('获取分类数据失败:', error);
      uni.showToast({
        title: '网络错误，请重试',
        icon: 'none',
      });
      loadStatus.value = 'loadmore';
    } finally {
      isLoading.value = false;
    }
  }

  function remove(id) {
    uWaterfallRef.value?.remove(id);
  }
  const toPreview = item => {
    uni.navigateTo({
      url: '/pages/preview/index?id=' + item.id + '&mode=category',
    });
  };
  function clear() {
    flowList.value = [];
    loadStatus.value = 'loadmore';
    // 重新获取数据
    fetchCategoryData();
  }

  onPageScroll(e => {
    scrollTop.value = e.scrollTop;
  });

  onLoad(() => {
    fetchCategoryData();
  });

  onReachBottom(() => {
    fetchCategoryData();
  });
</script>

<style>
  /* page不能写带scope的style标签中，否则无效 */
  page {
    background-color: rgb(240, 240, 240);
  }
</style>

<style lang="scss" scoped>
  @import '@/common/style/page-background.scss';
  .demo-warter {
    margin: 8rpx;
    position: relative;

    /* 照片部分不需要卡片样式 */
    u-lazy-load {
      border-radius: 8rpx;
      overflow: hidden;
      margin-bottom: 8rpx;
    }

    /* 信息部分保持卡片样式 */
    .demo-info {
      border-radius: 12rpx;
      background-color: #ffffff;
      padding: 12rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
    }
  }

  .u-close {
    position: absolute;
    top: 12rpx;
    right: 12rpx;
    background-color: rgba(0, 0, 0, 0.3);
    border-radius: 50%;
    padding: 6rpx;
    z-index: 10;
  }

  .demo-title {
    font-size: 26rpx;
    font-weight: 500;
    margin-bottom: 8rpx;
    color: #333;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .demo-tag {
    display: flex;
    align-items: center;
    margin-bottom: 8rpx;
    flex-wrap: wrap;
    gap: 6rpx;
  }

  .demo-tag-owner {
    background: #ff4757;
    color: #ffffff;
    padding: 4rpx 12rpx;
    border-radius: 16rpx;
    font-size: 20rpx;
    font-weight: 500;
  }

  .demo-tag-text {
    background: #0984e3;
    color: #ffffff;
    padding: 4rpx 12rpx;
    border-radius: 16rpx;
    font-size: 20rpx;
    font-weight: 500;
  }

  .demo-price {
    font-size: 28rpx;
    font-weight: 600;
    color: #ff4757;
    margin-bottom: 6rpx;
  }

  .demo-shop {
    font-size: 22rpx;
    color: #666;
    font-weight: 400;
    opacity: 0.8;
  }

  .wrap {
    padding: 16rpx;
    box-sizing: border-box;
    width: 100%;
    overflow-x: hidden;
  }

  /* 修复瀑布流右边被挤掉的bug */
  u-waterfall {
    width: 100% !important;

    ::v-deep .u-waterfall {
      width: 100% !important;

      .u-waterfall-left,
      .u-waterfall-right {
        width: calc(50% - 16rpx) !important;
        margin: 0 8rpx !important;
      }
    }
  }
</style>
